const axios = require("axios");
const cache = require('./cache');
const rds = require("./rds");

async function getWeworkAccessToken(agentId = 2000003) {
    const corpId = "wwdff5bd6a9e81395b";
    let secret = process.env.WK_CORP_SECRET;
    if (agentId === 2000003) secret = process.env.WK_CORP_SECRET;
    if (agentId === 1000026) secret = process.env.WK_ENG_SECRET;
    const key = `WEWORK-AGENT-${agentId}-ACCESS-TOKEN`;
    const cachedToken = cache.get(key);
    if (cachedToken) {
        return cachedToken;
    }
    const response = await axios.get(
        `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpId}&corpsecret=${secret}`
    );
    const weworkAccessToken = response?.data?.access_token ?? null;
    if (weworkAccessToken) {
        cache.set(key, weworkAccessToken);
        return weworkAccessToken;
    } else {
        throw new Error("Access token not found");
    }
}

async function getUserid(uid) {
    let wk_userid = "";
    if (uid > 0) {
        const query = "SELECT wk_userid FROM eb_wechat_user WHERE uid = ?";
        const [records] = await rds.query(query, [uid]);
        if (records && records.length > 0) {
            wk_userid = records[0].wk_userid || "";
        }
    }
    return wk_userid;
}

async function sendMessage(uid, content, agentid = 1000026) {
    const touser = await getUserid(uid);
    if (!touser) return false;

    try {
        const accessToken = await getWeworkAccessToken(agentid);
        const sendUrl = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${accessToken}`;
        const data = {
            touser,
            msgtype: "markdown",
            agentid: agentid,
            markdown: { content },
        };

        const response = await axios.post(sendUrl, data);
        return response.data.errcode === 0;
    } catch (error) {
        console.error("Error sending wework message:", error);
        return false;
    }
}

async function getWechatAccessToken(type = "weapp") {
    const appid = type === "weapp" ? process.env.WX_APP_ID : process.env.MP_APP_ID;
    const secret = type === "weapp" ? process.env.WX_APP_SECRET : process.env.MP_APP_SECRET;
    const key = `WECHAT-${type.toUpperCase()}-ACCESS-TOKEN`;

    try {
        const cachedToken = cache.get(key);
        if (cachedToken) {
            return cachedToken;
        }

        const response = await axios.post(
            "https://api.weixin.qq.com/cgi-bin/stable_token",
            {
                grant_type: "client_credential",
                appid,
                secret,
            }
        );

        if (response?.data?.access_token) {
            const accessToken = response.data.access_token;
            cache.set(key, accessToken, 6800);
            return accessToken;
        }

        throw new Error(`Failed to get access token: ${JSON.stringify(response.data)}`);
    } catch (error) {
        console.error(`Error getting WeChat access token for ${type}:`, error);
        throw error;
    }
}

async function clearAccessTokenCache(type = "weapp") {
    const key = `WECHAT-${type.toUpperCase()}-ACCESS-TOKEN`;
    cache.del(key);
}

module.exports = {
    getWeworkAccessToken,
    getUserid,
    sendMessage,
    getWechatAccessToken,
    clearAccessTokenCache
}; 
